package com.example.xiaozu.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.xiaozu.R;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AddProductActivity extends AppCompatActivity {
    private EditText etName, etDescription, etPrice;
    private ImageView ivProduct;
    private Uri selectedImageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);

        etName = findViewById(R.id.et_name);
        etDescription = findViewById(R.id.et_description);
        etPrice = findViewById(R.id.et_price);
        ivProduct = findViewById(R.id.iv_product);

        // 选择图片
        ivProduct.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, 100);
        });

        findViewById(R.id.btn_submit).setOnClickListener(v -> {
            String name = etName.getText().toString();
            String description = etDescription.getText().toString();
            String priceStr = etPrice.getText().toString();

            if (name.isEmpty() || description.isEmpty() || priceStr.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            double price;
            try {
                price = Double.parseDouble(priceStr);
            } catch (NumberFormatException e) {
                Toast.makeText(this, "请输入有效的价格", Toast.LENGTH_SHORT).show();
                return;
            }

            // 生成商品ID
            String productId = "product_" + System.currentTimeMillis();

            // 保存商品信息
            SharedPreferences.Editor editor = getSharedPreferences("products", MODE_PRIVATE).edit();
            editor.putString(productId + "_name", name);
            editor.putString(productId + "_description", description);
            editor.putFloat(productId + "_price", (float) price);

            // 保存图片URI（实际项目应保存到文件系统）
            if (selectedImageUri != null) {
                editor.putString(productId + "_image", selectedImageUri.toString());
            }
            editor.apply();

            Toast.makeText(this, "商品添加成功", Toast.LENGTH_SHORT).show();
            finish();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            ivProduct.setImageURI(selectedImageUri);
        }
    }
}
